<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Mapbox 多边形编辑</title>
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
  <!-- 使用本地化MapLibre GL JS和MapLibre Draw，无需API KEY，可离线部署 -->
  <script src="https://unpkg.com/maplibre-gl@3.6.1/dist/maplibre-gl.js"></script>
  <link href="https://unpkg.com/maplibre-gl@3.6.1/dist/maplibre-gl.css" rel="stylesheet" />
  <script src="https://unpkg.com/@maplibre/maplibre-gl-draw@0.4.1/dist/maplibre-gl-draw.js"></script>
  <link rel="stylesheet" href="https://unpkg.com/@maplibre/maplibre-gl-draw@0.4.1/dist/maplibre-gl-draw.css" type="text/css"/>
  <style>
    body { margin:0; padding:0; }
    #map { position:absolute; top:50px; bottom:0; width:100%; }
    .toolbar {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 50px;
      background: rgba(255,255,255,0.95);
      z-index: 20;
      display: flex;
      align-items: center;
      padding: 0 10px;
      gap: 10px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }
    .toolbar button {
      padding: 5px 12px;
      font-size: 14px;
      border: 1px solid #ccc;
      background: #f8f8f8;
      border-radius: 4px;
      cursor: pointer;
      transition: background 0.2s;
    }
    .toolbar button.active {
      background: #409eff;
      color: #fff;
      border-color: #409eff;
    }
  </style>
</head>
<body>
<div class="toolbar">
  <button id="btn-boundary">边界</button>
  <button id="btn-point">点</button>
  <button id="btn-line">线</button>
  <button id="btn-polygon">面</button>
  <button id="btn-edit">编辑</button>
  <button id="btn-save">保存</button>
</div>
<div id="map"></div>
<script>
  // 使用MapLibre GL JS，无需API KEY，可本地化部署
  const map = new maplibregl.Map({
    container: 'map',
    style: 'https://demotiles.maplibre.org/style.json', // 可替换为本地或自定义样式
    center: [116.397389, 39.908722],
    zoom: 10
  });

  let editMode = false;
  let currentDrawMode = null;

  // 兼容旧版MaplibreDraw命名
  const Draw = new MapLibreDraw({
    displayControlsDefault: false,
    controls: {},
    defaultMode: 'simple_select',
    modes: MapLibreDraw.modes
  });
  map.addControl(Draw);

  // 工具栏按钮
  const btnBoundary = document.getElementById('btn-boundary');
  const btnPoint = document.getElementById('btn-point');
  const btnLine = document.getElementById('btn-line');
  const btnPolygon = document.getElementById('btn-polygon');
  const btnEdit = document.getElementById('btn-edit');
  const btnSave = document.getElementById('btn-save');
  const buttons = [btnBoundary, btnPoint, btnLine, btnPolygon, btnEdit];

  function setActive(btn) {
    buttons.forEach(b => b.classList.remove('active'));
    if (btn) btn.classList.add('active');
  }

  btnBoundary.onclick = function() {
    setActive(btnBoundary);
    currentDrawMode = 'draw_polygon';
    Draw.changeMode('draw_polygon');
  };
  btnPoint.onclick = function() {
    setActive(btnPoint);
    currentDrawMode = 'draw_point';
    Draw.changeMode('draw_point');
  };
  btnLine.onclick = function() {
    setActive(btnLine);
    currentDrawMode = 'draw_line_string';
    Draw.changeMode('draw_line_string');
  };
  btnPolygon.onclick = function() {
    setActive(btnPolygon);
    currentDrawMode = 'draw_polygon';
    Draw.changeMode('draw_polygon');
  };
  btnEdit.onclick = function() {
    setActive(btnEdit);
    editMode = !editMode;
    if (editMode) {
      Draw.changeMode('simple_select');
      btnEdit.textContent = '结束编辑';
    } else {
      Draw.changeMode('simple_select');
      btnEdit.textContent = '编辑';
    }
  };

  // 支持删除选中要素
  map.on('keydown', function(e) {
    if ((e.key === 'Delete' || e.key === 'Backspace') && editMode) {
      const selected = Draw.getSelectedIds();
      selected.forEach(id => Draw.delete(id));
    }
  });
  map.getContainer().tabIndex = 0; // 使div可聚焦接收键盘事件

  // 保存按钮
  btnSave.onclick = function() {
    savePolygons();
  };

  // 保存多边形/点/线数据，单位为经纬度
  function savePolygons() {
    const data = Draw.getAll();
    // 只保留经纬度坐标
    const features = data.features.map(f => {
      return {
        type: f.type,
        geometry: f.geometry,
        properties: f.properties || {}
      };
    });
    // 通过QWebChannel发送到Qt
    if (window.qt && window.qt.webChannelTransport) {
      if (!window.channel) {
        new QWebChannel(window.qt.webChannelTransport, function(channel) {
          window.channel = channel;
          if (channel.objects && channel.objects.bridge) {
            channel.objects.bridge.receiveGeoJSON(JSON.stringify(features));
          }
        });
      } else if (window.channel.objects && window.channel.objects.bridge) {
        window.channel.objects.bridge.receiveGeoJSON(JSON.stringify(features));
      }
    } else {
      // 没有QWebChannel时弹窗
      alert(JSON.stringify(features, null, 2));
    }
  }

  // 可供Qt调用
  window.savePolygons = savePolygons;

  // QWebChannel支持
  // <script src="qrc:///qtwebchannel/qwebchannel.js"></script> 需在Qt端注入
</script>
</body>
</html>
